<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="title">校园二手书交易平台</h2>
      
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="账号密码登录" name="account">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="login-form">
            <el-form-item prop="username">
              <el-input 
                v-model="loginForm.username" 
                prefix-icon="el-icon-user"
                placeholder="请输入用户名">
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="请输入密码">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading.login" @click="handleLogin" class="login-btn">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="短信登录" name="sms">
          <el-form :model="smsForm" :rules="smsRules" ref="smsForm" class="login-form">
            <el-form-item prop="phone">
              <el-input 
                v-model="smsForm.phone" 
                prefix-icon="el-icon-mobile-phone"
                placeholder="请输入手机号">
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="code-input">
                <el-input 
                  v-model="smsForm.code" 
                  prefix-icon="el-icon-message"
                  placeholder="请输入验证码">
                </el-input>
                <el-button 
                  type="primary" 
                  :loading="loading.smsCode"
                  :disabled="smsCountdown > 0"
                  @click="sendSmsCode" 
                  class="send-code-btn">
                  {{ smsCountdown > 0 ? `${smsCountdown}秒后重试` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading.smsLogin" @click="handleSmsLogin" class="login-btn">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="邮箱登录" name="email">
          <el-form :model="emailForm" :rules="emailRules" ref="emailForm" class="login-form">
            <el-form-item prop="email">
              <el-input 
                v-model="emailForm.email" 
                prefix-icon="el-icon-message"
                placeholder="请输入邮箱">
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="code-input">
                <el-input 
                  v-model="emailForm.code" 
                  prefix-icon="el-icon-message"
                  placeholder="请输入验证码">
                </el-input>
                <el-button 
                  type="primary" 
                  :loading="loading.emailCode"
                  :disabled="emailCountdown > 0"
                  @click="sendEmailCode" 
                  class="send-code-btn">
                  {{ emailCountdown > 0 ? `${emailCountdown}秒后重试` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="loading.emailLogin" @click="handleEmailLogin" class="login-btn">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="register-now">
        还没有账号？<el-button type="text" @click="$router.push('/register')">立即注册</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'LoginPage',
  data() {
    return {
      activeTab: 'account',
      loginForm: {
        username: '',
        password: ''
      },
      smsForm: {
        phone: '',
        code: ''
      },
      emailForm: {
        email: '',
        code: ''
      },
      loading: {
        login: false,
        smsLogin: false,
        emailLogin: false,
        smsCode: false,
        emailCode: false
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      smsRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      emailRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      smsCountdown: 0,
      emailCountdown: 0
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading.login = true
          request.post('/api/login', this.loginForm)
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('登录成功')
                localStorage.setItem('authentication', response.data.data.token)
                this.$router.replace('/home')
              } else {
                this.$message.error(response.data.msg || '登录失败')
              }
            })
            .catch(error => {
              console.error('登录请求失败:', error)
              this.$message.error('登录失败，请稍后重试')
            })
            .finally(() => {
              this.loading.login = false
            })
        }
      })
    },
    handleSmsLogin() {
      this.$refs.smsForm.validate(valid => {
        if (valid) {
          this.loading.smsLogin = true
          request.post('/api/login/sms', this.smsForm)
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('登录成功')
                localStorage.setItem('authentication', response.data.data.token)
                this.$router.replace('/home')
              } else {
                this.$message.error(response.data.msg || '登录失败')
              }
            })
            .catch(error => {
              console.error('登录请求失败:', error)
              this.$message.error('登录失败，请稍后重试')
            })
            .finally(() => {
              this.loading.smsLogin = false
            })
        }
      })
    },
    handleEmailLogin() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          this.loading.emailLogin = true
          request.post('/api/login/email', this.emailForm)
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('登录成功')
                localStorage.setItem('authentication', response.data.data.token)
                this.$router.replace('/home')
              } else {
                this.$message.error(response.data.msg || '登录失败')
              }
            })
            .catch(error => {
              console.error('登录请求失败:', error)
              this.$message.error('登录失败，请稍后重试')
            })
            .finally(() => {
              this.loading.emailLogin = false
            })
        }
      })
    },
    sendSmsCode() {
      this.$refs.smsForm.validateField('phone', (errorMessage) => {
        if (!errorMessage) {
          this.loading.smsCode = true
          request.get('/api/sms/sendcode', { params: { phone: this.smsForm.phone } })
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('验证码已发送')
                this.startSmsCountdown()
              } else {
                this.$message.error(response.data.msg || '发送失败')
              }
            })
            .catch(error => {
              console.error('发送验证码失败:', error)
              this.$message.error('发送失败，请稍后重试')
            })
            .finally(() => {
              this.loading.smsCode = false
            })
        }
      })
    },
    sendEmailCode() {
      this.$refs.emailForm.validateField('email', (errorMessage) => {
        if (!errorMessage) {
          this.loading.emailCode = true
          request.post('/api/email/code', { email: this.emailForm.email })
            .then(response => {
              if (response.data.code === 1) {
                this.$message.success('验证码已发送')
                this.startEmailCountdown()
              } else {
                this.$message.error(response.data.msg || '发送失败')
              }
            })
            .catch(error => {
              console.error('发送验证码失败:', error)
              this.$message.error('发送失败，请稍后重试')
            })
            .finally(() => {
              this.loading.emailCode = false
            })
        }
      })
    },
    startSmsCountdown() {
      this.smsCountdown = 60
      const timer = setInterval(() => {
        this.smsCountdown--
        if (this.smsCountdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    startEmailCountdown() {
      this.emailCountdown = 60
      const timer = setInterval(() => {
        this.emailCountdown--
        if (this.emailCountdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

.login-box {
  width: 420px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  margin: 20px;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.login-tabs {
  margin-top: 20px;
}

.login-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background: linear-gradient(90deg, transparent, #667eea, transparent);
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  color: #606266;
  transition: all 0.3s;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #667eea;
  font-weight: 500;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background-color: #667eea;
}

.login-form {
  margin-top: 20px;
}

.login-form :deep(.el-input__inner) {
  height: 45px;
  line-height: 45px;
  border-radius: 10px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  padding-left: 40px;
  font-size: 14px;
}

.login-form :deep(.el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.login-form :deep(.el-input__prefix) {
  left: 12px;
}

.login-form :deep(.el-input__prefix .el-input__icon) {
  font-size: 18px;
  color: #909399;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input :deep(.el-input) {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  height: 45px;
  border-radius: 10px;
  font-size: 14px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s;
}

.send-code-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.send-code-btn:disabled {
  background: #dcdfe6;
  color: #909399;
  cursor: not-allowed;
}

.login-btn {
  width: 100%;
  height: 45px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s;
  letter-spacing: 1px;
}

.login-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.login-btn:active {
  transform: translateY(0);
}

.register-now {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.register-now .el-button {
  font-size: 14px;
  color: #667eea;
  font-weight: 500;
  transition: all 0.3s;
}

.register-now .el-button:hover {
  color: #764ba2;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media screen and (max-width: 480px) {
  .login-box {
    width: 90%;
    padding: 30px 20px;
    margin: 15px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .login-form :deep(.el-input__inner) {
    height: 40px;
    line-height: 40px;
  }
  
  .login-btn, .send-code-btn {
    height: 40px;
  }
  
  .send-code-btn {
    width: 100px;
    font-size: 12px;
  }
}
</style>